﻿namespace SimpleForum.Classes.Web
{
    using System;
    using System.Collections.Generic;
    using System.ComponentModel.Composition;
    using System.Linq;
    using System.Web.Mvc;

    using SimpleForum.Contracts;

    [Export]
    public class ImportControllerFactory : DefaultControllerFactory
    {
        [ImportMany] private IEnumerable<PartFactory<IController, IControllerMetadata>> ControllerFactories;

        public override IController CreateController(System.Web.Routing.RequestContext requestContext, string controllerName)
        {
            var factory = ControllerFactories
                .Where(f => f.Metadata.Name.Equals(controllerName, StringComparison.InvariantCultureIgnoreCase))
                .FirstOrDefault();

            if (factory != null) return factory.CreatePart();
            else return Microsoft.Practices.ServiceLocation.ServiceLocator.Current.GetInstance(GetControllerType(requestContext, controllerName)) as IController;
        }
    }
}